import React, { memo } from 'react'
import type { ReactNode } from 'react'
import { SongListWrapper } from './style'
import { useAppSelector } from '@/store'
import SongsItem from '@/components/songs-item'
import SongsPagination from '@/components/songs-pagination'
import { useEffect, useState } from 'react'
import { useAppDispatch } from '@/store'
import { fetchChangeCategoryAction } from '../../store/songs'
import type { PlaylistItemType } from '../../store/type'


interface IProps {
  children?: ReactNode
}

const SongsList: React.FC<IProps> = () => {
  const dispatch = useAppDispatch()
  const { currentCategoryList, currentCategory, PER_PAGE_NUMBER } = useAppSelector((state) => ({
    currentCategoryList: state.songs.currentCategoryList,
    currentCategory: state.songs.currentCategory as string,
    PER_PAGE_NUMBER: state.songs.PER_PAGE_NUMBER as number
  }))

  const [currentPage, setCurrentPage] = useState(1)

  useEffect(() => {
    setCurrentPage(1)
  }, [currentCategory])

  function onPageChange(page: number) {
    setCurrentPage(page)
    const offset = (page - 1) * PER_PAGE_NUMBER
    dispatch(
      fetchChangeCategoryAction({
        cat: currentCategory,
        offset,
        limit: PER_PAGE_NUMBER
      })
    )
  }
  return (
    <SongListWrapper>
      <div className="songs-list">
        {currentCategoryList.playlists.map((item: PlaylistItemType, index: number) => {
          return <SongsItem key={index} info={item} right={30} />
        })}
      </div>
      <SongsPagination
        currentPage={currentPage}
        total={currentCategoryList?.total ?? 0}
        onPageChange={onPageChange}
      ></SongsPagination>
    </SongListWrapper>
  )
}

export default memo(SongsList)
